<template>
	<div class="limited">
		<el-row>
			<el-col :span="6">
				<div class="left-box">
					<div class="store-header flex_between">
						<div class="flex_between flex1">
							<div class="">
								<span class="bold font_size16">多仓库</span>
								<span class="font_size12 ml10 font_black7">开启后1个仓库可以设置多个仓库</span>
							</div>
							<el-switch @change="comBaseSetHandle" v-model="ismstore" :active-value="'1'"
								:inactive-value="'2'"></el-switch>
						</div>
						<template v-if="ismstore == '1'">
							<div class="ml10 mr10 font_black7">|</div>
							<div class="iconBox">
								<text class="icon-font search-icon" @click="addOrEdt">&#xe606;</text>
							</div>
						</template>
					</div>
					<LeftList ref="leftListRef" :templates="templates" :listData="listData"
						:selectedIndex.sync="selectedIndex" :lLoading="lLoading" :lNoMore="lNoMore" @loadFun="loadFun"
						@clickItem="clickItem">
						<div slot-scope="{row}" slot="name" class="">
							<div class="flex_row" style="align-items: flex-start;">
								<div class="img-box">
									<el-image class="img" :src="row.imgs"></el-image>
								</div>
								<div class="flex1">
									<div class="flex_between">
										<span class="font_size16 bold mr10">{{ row.name }}</span>
										<el-tag size="mini" :type="row.status == 1 ? '' : 'info'">{{ row.status == 1 ?
											'启用' : '未启用'
										}}</el-tag>
									</div>
									<div class="flex_between">
										<div class="mr10">
											<span class="font_black7 ellipsis2"
												:title="row.district || '' + row.address || ''">{{
													row.district || '' }}{{ row.address || '' }}</span>
										</div>
										<el-tag size="mini" v-if="row.base == 1" type="warning">初始仓库</el-tag>
									</div>
								</div>
							</div>
						</div>
					</LeftList>
				</div>
			</el-col>
			<el-col :span="18">
				<div class="rigth-box">
					<div class="rigth-box-content">
						<el-form ref="formRef" :model="objectForm" :rules="objectRules" label-width="140px">
							<el-form-item label="仓库图标">
								<div class="active-box">
									<UploadPhotos :list="photoList" @update:list="updatePhotoList" :limit="1" />
								</div>
							</el-form-item>
							<el-form-item label="仓库名称" prop="name">
								<el-input v-model="objectForm.name" class="input-w" placeholder="请填写仓库名称" maxlength="50"
									show-word-limit></el-input>
							</el-form-item>
							<el-form-item label="负责人" prop="uid_mname">
								<!-- 将@click改为.native修饰符，确保事件能正确绑定到原生DOM元素 -->
								<el-input type="text" v-model="objectForm.uid_mname" class="input-w"
									placeholder="请点击选择负责人" readonly @click.native="openUserSelectPopup"></el-input>
							</el-form-item>
							<el-form-item label="联系电话" prop="cellphone">
								<el-input type="number" maxlength="11" v-model="objectForm.cellphone" class="input-w"
									placeholder="请填写联系电话" @input="handlePhoneInput"></el-input>
							</el-form-item>
							<el-form-item label="仓库地址" prop="address">
								<el-input type="text" v-model="objectForm.address" class="input-w"
									placeholder="请填写仓库地址"></el-input>
							</el-form-item>
							<el-form-item label="备注" prop="txt">
								<el-input type="text" v-model="objectForm.txt" class="input-w"
									placeholder="备注"></el-input>
							</el-form-item>
							<el-form-item label="启用仓库" prop="status">
								<el-switch v-model="objectForm.status" :active-value="'1'"
									:inactive-value="'2'"></el-switch>
							</el-form-item>
						</el-form>
					</div>
					<div class="rigth-box-footer flex_between">
						<div class="summary-info"></div>
						<div class="action-buttons">
							<el-button type="primary" @click="sbumitHandle" size="large" class="btn-confirm"> 保 存
							</el-button>
						</div>
					</div>
				</div>
			</el-col>
		</el-row>
		<!-- 选择人员 -->
		<popServiceSelect :page_i="page_i" ref="popServiceSelectRef" @getServiceData="getUserData">
		</popServiceSelect>
	</div>
</template>

<script setup>
import { ref, onMounted, getCurrentInstance } from '@vue/composition-api'
import LeftList from "@/pages/setting/components/leftList.vue"
import config from "@/js/conf/Config.js"
import API from "@/js/conf/api.js"
import { useCommonHooks } from '@/hooks/useCommonHooks.js'
import UploadPhotos from "@/components/commV2/UploadPhotos/index.vue"
import popServiceSelect from "@/components/appointment/popServiceSelect.vue"

// 使用全局状态
const { stateHooks } = useCommonHooks()

const maxPnum = 20
// 获取当前组件实例
const { proxy } = getCurrentInstance()

const templates = ref([{
	type: "slot",
	key: "name",
}, {
	type: "slot",
	key: "address",
},
])
const ismstore = ref('1')
const photoList = ref([])
// 表单数据
const objectForm = ref({
	name: '', // 仓库名称
	uid_mname: '', // 负责人
	uid_m: '', // 负责人id
	cellphone: '', // 联系电话
	address: '', // 仓库地址
	txt: '', // 备注
	status: '1', // 启用状态，默认启用
	code_s: '', // 仓库缩写（验证规则中存在但表单未显示）
	districtCodeArr: [] // 地区代码数组（验证规则中存在）
})
const detailID = ref('')

// 在表单验证规则中添加cellphone验证
const objectRules = ref({
	name: [
		{ required: true, message: '请输入仓库名称', trigger: 'blur' }
	],
	code_s: [
		{ required: true, message: '请输入仓库缩写', trigger: 'blur' }
	],
	districtCodeArr: [
		{ required: true, message: '请选择所在地区', trigger: 'change' }
	],
	address: [
		{ required: true, message: '请输入详细地址', trigger: 'blur' }
	],
	cellphone: [
		{ required: true, message: '请输入联系电话', trigger: 'blur' },
		{ pattern: /^1[3-9]\d{9}$/, message: '请输入11位手机号码', trigger: 'blur' }
	]
})

// 添加电话号码输入处理函数
const handlePhoneInput = () => {
	if (objectForm.value.cellphone && objectForm.value.cellphone.toString().length > 11) {
		// 截取前11位数字
		objectForm.value.cellphone = objectForm.value.cellphone.toString().substring(0, 11)
	}
}

const page_i = ref(4)
const popServiceSelectRef = ref(null)

// 打开选择人员弹窗
const openUserSelectPopup = () => {
	if (popServiceSelectRef.value) {
		console.log('openUserSelectPopup - 弹窗引用存在')
		try {
			if (popServiceSelectRef.value.show) {
				popServiceSelectRef.value.show()
			} else if (popServiceSelectRef.value.open) {
				popServiceSelectRef.value.open()
			} else {
				// 尝试初始化数据
				popServiceSelectRef.value.initData({ list: [], selectType: '2' })
			}
		} catch (error) {
			console.error('打开弹窗时出错:', error)
		}
	} else {
		console.warn('popServiceSelectRef.value 为 null 或 undefined')
		// 备用方案：如果组件引用获取不到，尝试通过proxy获取
		if (proxy && proxy.$refs && proxy.$refs.popServiceSelectRef) {
			console.log('通过proxy获取到组件引用')
			proxy.$refs.popServiceSelectRef.initData({ list: [], selectType: '2' })
		}
	}
}

// 处理选择的用户数据
const getUserData = (data) => {
	console.log('getUserData', data)
	objectForm.value.uid_mname = data.mname || data.name // 设置负责人姓名
	objectForm.value.uid_m = data.uid || '' // 设置负责人id
	objectForm.value.cellphone = data.cellphone || '' // 设置联系电话
}

const listData = ref([])
const selectedIndex = ref(0)
const pfrom = ref(0)
const lLoading = ref(false)
const lNoMore = ref(false)

const loadFun = () => {
	if (lNoMore.value || lLoading.value) return
	pfrom.value += 20
	if (listData.value.length > 0) {
		pfrom.value += 20
		getEventLs(false)
	}
}

const getEventLs = async (t = true) => {
	lLoading.value = true
	if (t == true) {
		pfrom.value = 0
		listData.value = []
	}
	let param = {
		issell: 0,
		status: 0,
	}
	try {
		let res = await proxy.$api({ url: config.ck_store_store_ls, data: param })
		lLoading.value = false
		if (res.status == 1) {
			let result = res.data.ck
			if (result && result.length > 0) {
				listData.value.push(...result)
				// 确保索引在有效范围内
				const validIndex = Math.min(selectedIndex.value, listData.value.length - 1)
				if (t == true) {
					detailID.value = listData.value[validIndex]?.id
					getShopInfo()
				}
				if (res.status == 1 && result.ls.length < maxPnum) {
					lNoMore.value = true
				} else {
					lNoMore.value = false
				}
			} else {
				lNoMore.value = true;
			}
		} else {
			lNoMore.value = true
		}
	} catch (error) {
		lLoading.value = false
		lNoMore.value = true
	} finally {
		lLoading.value = false
	}
}

const getShopInfo = async () => {
	try {
		let res = await proxy.$api({
			url: config.ck_store_info, data: {
				id: detailID.value
			}
		})
		let result = res.data || {}
		if (res.status == 1) {
			objectForm.value = result
			photoList.value = result.imgs ? [{ url: result.imgs }] : []
		}
	} catch (error) {
		console.error('获取仓库信息失败:', error)
	} finally {
	}
}

const comBaseSetHandle = async () => {
	try {
		let res = await proxy.$api({
			url: config.compset_base_set, data: {
				ismstore: ismstore.value
			}
		})
		if (res.status == 1) {
			getEventLs(true)
		}
	} catch (error) {
		console.error('获取仓库信息失败:', error)
	}
}

const clickItem = (index) => {
	detailID.value = listData.value[index]?.id
	getShopInfo()
}

const addOrEdt = () => {
	resetFun()
	detailID.value = 0
	selectedIndex.value = null
}

const resetFun = () => {
	objectForm.value = {
		name: '', // 仓库名称
		uid_mname: '', // 负责人
		uid_m: '', // 负责人
		cellphone: '', // 联系电话
		address: '', // 仓库地址
		txt: '', // 备注
		status: '1', // 启用状态，默认启用
		code_s: '', // 仓库缩写（验证规则中存在但表单未显示）
		districtCodeArr: [] // 地区代码数组（验证规则中存在）
	}
	photoList.value = []
}

const updatePhotoList = (newList) => {
	photoList.value = newList
}

const sbumitHandle = async () => {
	try {
		// 表单验证
		const valid = await proxy.$refs.formRef.validate()
		if (!valid) {
			proxy.$message({
				message: '请完善表单信息',
				type: 'warning'
			})
			return
		}
		let params = {
			...objectForm.value,
			imgs: photoList.value.length > 0 ? photoList.value[0].name : ''
		}
		let res = await proxy.$api({ url: config.ck_store_save, data: params })
		if (res.status == 1) {
			proxy.$message({
				message: '保存成功',
				type: 'success'
			})
			getEventLs()
		} else {
			proxy.$message({
				message: res.msg || '保存失败',
				type: 'error'
			})
		}
	} catch (error) {
		console.error('保存失败:', error)
		proxy.$message({
			message: '请检查表单内容',
			type: 'error'
		})
	}
}

onMounted(async () => {
	let res = await API.get_compset_base_info()
	if (res.status == 1) {
		ismstore.value = res.data.ismstore
	}
	getEventLs()
})

</script>

<style lang="scss" scoped>
div {
	box-sizing: border-box;
}

.limited {
	max-height: 100vh;
	height: calc(100vh - 90px);
	/* 确保最小高度为视窗高度 */
	overflow: hidden;

	::v-deep .el-row {
		height: 100%;
	}

	::v-deep .el-col {
		height: 100%;
	}

	.left-box,
	.rigth-box {
		width: 100%;
		padding: 0 10px 0 10px;
		height: 100%;

		.iconBox {
			font-size: 26px;
			cursor: pointer;
			position: relative;
			top: -6px;

			.search-icon {
				font-size: 20px;
				color: #333;
			}
		}
	}

	.left-box {
		border-right: 1px solid #e6e6e6;

		.store-header {
			box-sizing: border-box;
			border: 1px solid #f1f1f1;
			border-radius: 4px;
			box-shadow: 0 1px 2px rgba(0, 0, 0, .1);
			padding: 0 14px;
			height: 60px;
		}

		.img-box {
			width: 60px;
			height: 60px;
			border-radius: 4px;
			margin-right: 10px;

			.img {
				width: 100%;
				height: 100%;
				border-radius: 4px;
				object-fit: cover;
			}
		}
	}

	.rigth-box {
		box-sizing: border-box;
		display: flex;
		flex-direction: column;
		height: 100%;
		/* 确保容器有明确高度 */
		overflow: hidden;

		.rigth-box-content {
			box-sizing: border-box;
			flex: 1;
			height: 0;
			/* 关键：让flex-grow生效 */
			min-height: 0;
			/* 允许收缩 */
			padding-right: 100px;
			overflow-y: auto;
			/* 内容溢出时显示滚动条 */
		}

		.rigth-box-footer {
			flex-shrink: 0;
			/* 防止footer被压缩 */
			border-top: 1px solid #f1f1f1;
			margin-top: 10px;
			padding: 14px 10px 4px;

			.summary-info {
				display: flex;
				align-items: center;
				gap: 16px;
			}

			.action-buttons {
				display: flex;
				gap: 12px;

				.btn-cancel {
					border-color: #cbd5e1;
					color: #64748b;
				}

				.btn-confirm {
					background-color: #3b82f6;
					border-color: #3b82f6;
				}
			}
		}
	}
}

.input-w {
	width: 400px;

	&[readonly] {
		cursor: pointer;
		background-color: #fafafa;
	}
}
</style>